const { Category } = require('../../../model/category');
const { ChildCategory } = require('../../../model/childCategory');

module.exports = async (req, res) => {
    let list = []
    let categories = await Category.find().sort({ _id: -1 })
    // 标记是否全部结果都查询回来了
    let flag = 0
    categories.forEach((item, i) => {
        // 异步查询，不一定先查询的先得到结果
        ChildCategory.find({ parent: item._id }).sort({ _id: -1 }).then(arr => {
            list[i] = {
                ...item.toObject(),
                children: arr
            }
            flag++
            console.log(flag)
            if (flag >= categories.length) {
                console.log('完成了')
                res.json({
                    data: list
                })
            }
        })
    })
}